<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2015-5-20
 * Time: 10:02
 * this file is for single image upload function
 */

namespace doumiaoduo\ueditor;


use yii\widgets\InputWidget;
use yii\helpers\Html;
use yii\helpers\Json;
use yii\helpers\ArrayHelper;

class ImageUploadSingle extends InputWidget
{


    public $clientOptions = [];

    public $serverParam = [];

    public $buttonOptions = [];

    public $view;
    public $asset;

    public function init()
    {
        parent::init();
        $id = str_replace('-', '_', $this->options['id']);
        if (isset($this->clientOptions['serverUrl'])) {
            $this->clientOptions['serverUrl'] = str_replace('action', 'uploadimage', $this->clientOptions['serverUrl']);
            $this->clientOptions['serverUrl'] = str_replace(urlencode('action'), 'uploadimage', $this->clientOptions['serverUrl']);
        }
        $this->clientOptions['csrf-param'] = \Yii::$app->request->csrfParam;
        $this->clientOptions['csrf-token'] = \Yii::$app->request->getCsrfToken();
        $this->clientOptions['isShow'] = false;
        $this->buttonOptions['id'] = isset($this->buttonOptions['id']) ? $this->buttonOptions['id'] : "image_upload_button_{$this->options['id']}";
        $this->view = $this->getView();
        $this->asset = ImageUploadSingleAsset::register($this->view);
    }

    public function run()
    {
        $strHtml = '';

        if ($this->hasModel()) {
            $strHtml .= Html::activeHiddenInput($this->model, $this->attribute, $this->options);
        } else {
            $strHtml .= Html::hiddenInput($this->name, $this->value, $this->options);
        }

        $strHtml .= '<div class="containdiv"><div id="' . $this->buttonOptions['id'] . '" style="text-align:center;">';
        $this->value = $this->hasModel() ? Html::getAttributeValue($this->model, $this->attribute) : $this->value;//如果当前部件从属于一个model，那么当前输入框的值就根据model和属性获取，否则就使用当前值
        $imgurl = !empty($this->value) ? $this->value : $this->asset->baseUrl . "/upload_pic.png";//如果当前图片的url值存在就使用已经上传的图片的值；否则显示默认的图片
        $strHtml .= Html::img($imgurl,['width'=>'80px','height'=>'80px']);
        $strHtml .= '</div>';
        $strHtml .= '<div class="clipperdiv"><button>裁剪图片</button><br/><button class="cancelimg">取消图片</button></div></div>';

        echo $strHtml;
        $this->registerClientScript();
    }

    public function registerClientScript()
    {
        $jss = "";
        $jss .= <<<JS
var uploader = WebUploader.create({
        auto:true,
        swf: '{$this->asset->baseUrl}/ueditor/third-party/webuploader/Uploader.swf',
        server: '{$this->clientOptions['serverUrl']}',
        pick: '#{$this->buttonOptions['id']}',
        fileVal: 'upfile',
        accept: {
        title:'Images',
        extensions:'gif,jpg,jpeg,bmp,png',
        mimeTypes: 'image/*'
        },
        resize: false,
        });
        uploader.on('uploadBeforeSend', function( block, data, headers) {//文件上传前添加参数
$.extend(data, {
'{$this->clientOptions['csrf-param']}': '{$this->clientOptions['csrf-token']}',
    });
	});
JS;

        //监听fileQueued事件
        $jss .= <<<JS
uploader.on( 'fileQueued', function( file ) {
var li = '<div id=\"'+file.id+'\" class=\"file-item thumbnail\">'+
'</div>';
        img = $('#{$this->buttonOptions['id']} img');
        $('#thelist').append(li);
//获取上传图片的宽和高

    uploader.makeThumb( file, function( error, src ) {
        if ( error ) {
            img.replaceWith('<span>不能预览</span>');
            return;
        }
        img.attr( 'src', src );
    },80,80);
});
JS;

//文件上传进度
        /**$jss .= <<<JS
         * uploader.on( 'uploadProgress',function(file,percentage) {
         * alert(percentage);
         * var percent = $('.webuploader-pick').find('.progress .text');
         * var percentbg = $('.webuploader-pick').find('.progress .percentage');
         * if ( !percent.length ) {
         * percent = $('<p class="progress"><span class="text">0%</span><span class="percentage" style="width: 50%;"></span></p>')
         * .appendTo('.webuploader-pick')
         * .find('.text');
         * percentbg = $('.progress .percentage');
         * }
         * percent.text(percentage * 100+"%");
         * percentbg.css( 'width', percentage * 100 + '%' );
         * });
         * JS;*/

        //文件上传成功
        $jss .= <<<JS
uploader.on( 'uploadSuccess', function( file,response) {
    $( '#'+file.id ).addClass('upload-state-done');
    //将文件信息存储起来
    $('#{$this->options['id']}').val(response.url);

    /**var fileinfo = '<input type="text" value="'+response.url+'"/>';
    var percent = $( '#'+file.id ).append(fileinfo);*/
});
JS;
        $jss .= <<<JS
uploader.on( 'uploadError', function( file ) {
var li = $( '#'+file.id ),
        error = li.find('div.error');
        if ( !error.length ) {
    error = $('<div class="error"></div>').appendTo(li);
        }
    error.text('上传失败');
    });
JS;

        //完成上传完了，成功或失败，先删除进度条
        $jss .= <<<JS
uploader.on( 'uploadComplete', function( file ) {
    $( '#'+file.id ).find('.progress').remove();
});
JS;
//点击取消图片的事件
        $jss .= <<<JS
$(".cancelimg").on('click',function(){
  $('#{$this->options['id']}').val('');
  $('#{$this->buttonOptions['id']} img').attr('src','{$this->asset->baseUrl}/upload_pic.png');
  //$('#{$this->buttonOptions['id']}').css({"width":"165px","height":"33px"});
  return false;
});
JS;
        $this->view->registerJs($jss);
    }

}